/*

- 文件名：proTrackController.java
- 版权：Copyright by www.infopub.top
- 描述：
- 修改人：huangxiaolang
- 修改时间：2020年1月15日
- 跟踪单号：
- 修改单号：
- 修改内容：
  */

package top.infopub.mgr.mkt.web;


import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.ProcessService;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.domain.ProTrackDomain;
import top.infopub.mgr.mkt.jsonvo.CollectJsonVo;
import top.infopub.mgr.mkt.service.*;
import top.infopub.mgr.mkt.vo.CollectionInfoVo;
import top.infopub.mgr.mkt.vo.InvestmentInfoVo;
import top.infopub.mgr.mkt.vo.ProTrackVo;
import top.infopub.mgr.mkt.vo.TrackVo;
import top.infopub.mgr.sg.service.CitySurveyService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.model.flow.Process;
import top.infopub.model.mkt.*;
import top.infopub.model.sg.CitySurvey;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;


@Controller
@RequestMapping("/proTrack")
public class ProTrackController extends GenericFlowController {

    @Autowired
    private ProTrackService proTrackService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CitySurveyService citySurveyService;

    @Autowired
    private DeciProService deciProService;

    @Autowired
    private InquiryProService inquiryService;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private PreProjectService preProjectService;

    @Autowired
    private ProProgressService proProgressService;

    @Autowired
    private ProjectInfoService  projectInfoService;

    @Autowired
    private ProProcessManageService proProcessManageService;
    @Autowired
    private ProcessService processService;
    @RequestMapping("/list")
    public String list() {
        return "mkt/lay-proTrack-list";
    }

    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ProTrackDomain> queryDataByCondition(TrackVo trackVo,ParamPage paramPage)
        throws ParseException {
        Page<ProTrackDomain> page = new Page<ProTrackDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        if ("0".equals(trackVo.getProStage())){
            trackVo.setProStage(null);
        }
        if (StringUtils.isNotBlank(trackVo.getStartTrackDate())) {
            trackVo.setDate(DateUtils.parseDateByFormat(trackVo.getStartTrackDate(), "yyyy-MM-dd"));
        }
        page = proTrackService.selectByTrackVo(page, trackVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    @RequestMapping("/queryDataList")
    @ResponseBody
    public RspVo<ProTrackDomain> queryDataList(ProTrackVo proTrackVo, ParamPage paramPage)
            throws ParseException {
        Page<ProTrackDomain> page = new Page<ProTrackDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (proTrackVo.getEndDate() != null) {
            proTrackVo.setEndDate(DateUtils.addDays(proTrackVo.getEndDate(), 1));
        }
        if (proTrackVo.getEndTrackDate() != null) {
            proTrackVo.setEndTrackDate(DateUtils.addDays(proTrackVo.getEndTrackDate(), 1));
        }
        //proTrackVo.setAddBy(SessionUserUtils.getSessionAttributeForUserDtl().getId());
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        proTrackVo.setVisibleOrgIds(visibleOrgIds);
        page = proTrackService.selectByDomainWhere(page, proTrackVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * -我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<ProTrackDomain> queryMyCheckDataByCondition(ProTrackVo proTrackVo,
                                                             ParamPage paramPage) {
        Page<ProTrackDomain> page = new Page<ProTrackDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (proTrackVo.getEndDate() != null) {
            proTrackVo.setEndDate(DateUtils.addDays(proTrackVo.getEndDate(), 1));
        }
        // 增加addby
        proTrackVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = proTrackService.selectMyCheckByDomainWhere(page, proTrackVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        String hrStaffMktId = authorizationVO.getHrStaffId();
        //拿到所有预立项中的项目名称
        List<PreProject> preProjects = preProjectService.getPreProjectWithStaff(null, hrStaffMktId);
        request.setAttribute("allProName", preProjects); //可拿到项目名称集合
        List<CitySurvey> citys = new ArrayList<CitySurvey>();
        request.setAttribute("pubIncomeList", citys);
        return "mkt/lay-proTrack-add";
    }

    @RequestMapping("/addNew")
    public String toAddNew(HttpServletRequest request,String id,String type) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        //String hrStaffMktId = authorizationVO.getHrStaffId();
//        ProTrackDomain proTrack=proTrackService.selectProjectInfo(id,type);
//        request.setAttribute("track", proTrack);
        List<CitySurvey> citys = new ArrayList<CitySurvey>();
        request.setAttribute("pubIncomeList", citys);
        return "mkt/lay-proTrack-addNew";
    }

    @RequestMapping("/detailNew")
    public String detailNew(HttpServletRequest request,String id,String proCode) {
        request.setAttribute("id", id);
        request.setAttribute("proCode", proCode);
        return "mkt/lay-proTrack-detailNew";
    }

    /**
     *
     * @param request
     * @return  Map
//     * @see 带出去项目编号以及一般公共预算收入给前端的接口
     */
    @RequestMapping("/getPubIncome")
    @ResponseBody
    public Map<String, Object> getProPlotProId(HttpServletRequest request,String codeAndId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String[] codeAndIds = codeAndId.split("_");
            String proCode = codeAndIds[0]; //预立项对象的全局唯一项目id
            String id = codeAndIds[1]; //预立项的id
            PreProject preProject = preProjectService.selectByPrimaryKey(id);
            //查询最新决策记录
            Map<String, Object> mapWhere = new HashMap<String, Object>();
            mapWhere.put("proCode", proCode);
            mapWhere.put("processStatus", "9");
            mapWhere.put("orderCondition", "ADD_TIME desc");
            List<DeciPro> deciPros = deciProService.selectByMapWhere(mapWhere);
            if (CollectionUtils.isNotEmpty(deciPros)) {
                DeciPro deciPro = deciPros.get(0);
                map.put("sumAmount", deciPro.getSumAmount());
                map.put("sumCae", deciPro.getSumCae());
            }else {//查询最新资格预审记录
                List<InquiryPro> inquiryPros = inquiryService.selectByMapWhere(mapWhere);
                if (CollectionUtils.isNotEmpty(inquiryPros)) {
                    InquiryPro inquiryPro = inquiryPros.get(0);
//                    map.put("sumAmount", inquiryPro.getSumAmount());
//                    map.put("sumCae", inquiryPro.getSumCae());
                }else {//查询最新立项记录
                    List<SetupPro> setupPros = setupProService.selectByMapWhere(mapWhere);
                    if (CollectionUtils.isNotEmpty(setupPros)) {
                        SetupPro setupPro = setupPros.get(0);
//                        map.put("sumAmount", setupPro.getSumAmount());
//                        map.put("sumCae", setupPro.getSumCae());
                    }else {//查询最新预立项记录
                        List<PreProject> preProjects = preProjectService.selectByMapWhere(mapWhere);
//                        if (CollectionUtils.isNotEmpty(preProjects)) {
//                            preProject = preProjects.get(0);
//                            map.put("sumAmount", preProject.getSumAmount());
//                            map.put("sumCae", preProject.getSumCae());
//                        }else {//根据id查询预立项记录
//                            map.put("sumAmount", preProject.getSumAmount());
//                            map.put("sumCae", preProject.getSumCae());
//                        }
                    }
                }
            }
            //查询一般公共预算收入
//            CitySurvey city = citySurveyService.selectByPrimaryKey(preProject.getSgCityId());
//            map.put("pubIncome", city.getPubIncome());
        }
        catch (Exception e) {
            log.error("根据项目全局唯一编号ID获取项目信息异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 项目追踪-新增
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(HttpServletRequest request, ProTrack proTrack) throws ParseException {
        /*String codeAndId = request.getParameter("pro");
        String[] ci = codeAndId.split("_");
        proTrack.setProCode(ci[0]);
        proTrack.setSgCityId(ci[1]);
        proTrack.setHrStaffMktId(ci[2]);*/
        proTrackService.saveProTrack(proTrack);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
//            "市场事项 -新增项目追踪：项目名=" + proTrack.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    /***
     * *审批页面**
     *
     * ***/
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        ProTrack proTrack = new ProTrack();
        if (id!=null){
          proTrack = proTrackService.selectByPrimaryKey(id);
        }else if (proCode!=null){
          proTrack = proTrackService.selectByProCode(proCode);
        }
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("showFlag","0"); //默认不展示
        if (proTrack != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), proTrack.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(proTrack.getProcessId()) && proTrack.getProcessId().length() > 10) {
                request.setAttribute("processId", proTrack.getProcessId());
                Process process = processService.selectByPrimaryKey(proTrack.getProcessId());
                ProjectInfo byProCode = projectInfoService.findByProCode(proTrack.getProCode());
                if (process.getMaxIdx()>2 && "1".equals(byProCode.getIsTrack())){
                    request.setAttribute("showFlag","1");//节点大于两个并且已终止跟踪 只展示
                }else if(process.getMaxIdx()==2){
                    request.setAttribute("showFlag","2"); //节点只有两个 可选
                }
                String auditTabFlag = proProcessManageService.checkShowAuditTab(proTrack.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), proTrack.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("id",proTrack.getId());
        request.setAttribute("proCode",proCode);
        return "mkt/lay-projectTracking-detail";
    }
    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg,String isTrack) {
        //项目信息收集审批
        if (StringUtils.isNotBlank(isTrack)){
            proProcessManageService.auditProject(id, processId, status, auditMsg, isTrack);
        }else{
            proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        }
        return RspVo.getSuccessResponse();
    }


    @RequestMapping("/proTrackPage")
    @ResponseBody
    public RspVo<ProTrackDomain> proTrackPage(String proCode, ParamPage paramPage)
            throws ParseException {
        Page<ProTrackDomain> page = new Page<ProTrackDomain>();
        ProTrackVo proTrackVo = new ProTrackVo();
        proTrackVo.setProCode(proCode);
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = proTrackService.selectByTrackPage(page, proCode);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    @RequestMapping("/proTrackDetail")
    @ResponseBody
    public RspVo<ProTrackDomain> proTrackDetail(String proCode, ParamPage paramPage)
            throws ParseException {
        Page<ProTrackDomain> page = new Page<ProTrackDomain>();
        ProTrackVo proTrackVo = new ProTrackVo();
        proTrackVo.setProCode(proCode);
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = proTrackService.selectPageByDomainWhere(page, proTrackVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    @RequestMapping("/proTrackDevelopPage")
    @ResponseBody
    public RspVo<ProProgress> proTrackDevelopPage(String proCode, ParamPage paramPage)
            throws ParseException {
        Page<ProProgress> page = new Page<ProProgress>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = proProgressService.selectDevelop(page,proCode);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 项目最新进展不分页
     * **/
    @RequestMapping("/proTrackDevelop")
    @ResponseBody
    public RspVo proTrackDevelop(String proCode) {
        List<ProProgress> proProgresses = proProgressService.selectByProCode(proCode);
        return RspVo.getSuccessResponse(proProgresses);
    }

//    @RequestMapping("/toDealOrDetail1")
//    public String trackDetail(HttpServletRequest request,String proCode) {
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//        ProTrack proTrack = proTrackService.selectByProCode(proCode);
//        request.setAttribute("isAuditFlag", "0");
//        request.setAttribute("showFlag","0"); //默认不展示
//        if (proTrack != null) {
//            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), proTrack.getProcessStatus())) {
//                request.setAttribute("isAuditFlag", "1");
//            }
//            if (StringUtils.isNotBlank(proTrack.getProcessId()) && proTrack.getProcessId().length() > 10) {
//                request.setAttribute("processId", proTrack.getProcessId());
//                Process process = processService.selectByPrimaryKey(proTrack.getProcessId());
//                ProjectInfo byProCode = projectInfoService.findByProCode(proTrack.getProCode());
//                if (process.getMaxIdx()>2 && "1".equals(byProCode.getIsTrack())){
//                    request.setAttribute("showFlag","1");//节点大于两个并且已终止跟踪 只展示
//                }else if(process.getMaxIdx()==2){
//                    request.setAttribute("showFlag","2"); //节点只有两个 可选
//                }
//                String auditTabFlag = proProcessManageService.checkShowAuditTab(proTrack.getProcessId(), vo);
//                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), proTrack.getProcessStatus())
//                        && StringUtils.equals("0", auditTabFlag)) {
//                    request.setAttribute("isAuditFlag", "0");
//                }
//                request.setAttribute("auditTabFlag", auditTabFlag);
//            }
//        }
//        request.setAttribute("proCode", proCode);
//        return "mkt/lay-projectTracking-detail";
//    }

    /***
     *
     * 跟踪详情
     * ***/
    @RequestMapping("/queryCollectDetail")
    @ResponseBody
    public RspVo queryCollectDetail(String proCode) {
        //项目详情信息
        CollectJsonVo collectJsonVo = proTrackService.queryDetailById(proCode);
        return RspVo.getSuccessResponse(collectJsonVo);
    }

    /***
     *
     * 项目跟踪项目基础信息详情
     * ***/
    @RequestMapping("/getDetail")
    @ResponseBody
    public RspVo getDetail (String proCode){
      return proTrackService.queryDetail(proCode);
    }
    /***
     *
     * 查询项目编码
     * ***/
    @RequestMapping("/queryProCode")
    @ResponseBody
    public String queryProCode(String id) {
        //项目详情信息
        ProTrack proTrack = proTrackService.selectByPrimaryKey(id);
        return proTrack.getProCode();
    }
    /**
     /**
     * 项目跟踪
     * @return
     */
    @SuppressWarnings({"rawtypes"})

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    @ResponseBody
    public RspVo save(HttpServletRequest request, String bodyStr, Integer submitType){
        AuthorizationVO userDtl = SessionUserUtils.getSessionAttributeForUserDtl();
        String s = StringEscapeUtils.unescapeJava(bodyStr);
        CollectionInfoVo vo = JSON.parseObject(s,CollectionInfoVo.class);
        //项目信息
        ProjectInfo proInfo = new ProjectInfo();
        BeanUtils.copyProperties(vo.getProjectInfo(), proInfo);

        //更新项目合作方-MKT_AFTER_SUMMARY_COOP
        List<AfterSummaryCoop> summCoopList = vo.getSummary();
        for (AfterSummaryCoop asc : summCoopList) {
            asc.setId(null);
            asc.setProCode(vo.getProjectInfo().getProCode());
            asc.setAddBy(vo.getId());
            asc.setAddTime(new Date());
        }
        AfterSummaryCoop coop = new AfterSummaryCoop();
        coop.setId(null);
        coop.setSgCoopId(proInfo.getUnitId());
        coop.setCoopEffect("-1");
        coop.setCooperationType("-1");
        coop.setProCode(proInfo.getProCode());
        coop.setAddBy(vo.getId());
        coop.setAddTime(new Date());
        summCoopList.add(coop);

        //更新项目子项表格信息-MKT_PROJECT_SUB_INFO
        ProjectSubInfo proSubInfo = new ProjectSubInfo();
        proSubInfo.setProCode(vo.getProjectInfo().getProCode());
        if (vo.getItemName() != null && vo.getItemName().size() > 0) {
            proSubInfo.setTitleJson(JSON.toJSONString(vo.getItemName()));
        }
        if (vo.getInvestmentInfoVos() != null && vo.getInvestmentInfoVos().size() > 0) {
            proSubInfo.setContentJson(JSON.toJSONString(vo.getInvestmentInfoVos()));
            StringBuffer rowTotal = new StringBuffer();
            StringBuffer colTotal = new StringBuffer();
            int itivIdx = 0;
            int itivSize = vo.getInvestmentInfoVos().size();
            for (InvestmentInfoVo itiv : vo.getInvestmentInfoVos()) {
                if (itivIdx == (itivSize - 1)) {
                    for (BigDecimal tmpTotal : itiv.getList()) {
                        rowTotal.append(tmpTotal.toString());
                        rowTotal.append(",");
                    }
                    rowTotal.append(itiv.getTotal());
                }
                if (itivIdx > 2) {
                    colTotal.append(itiv.getTotal());
                    colTotal.append(",");
                }
                itivIdx++;
            }
            if (colTotal.length() > 0) colTotal.deleteCharAt(colTotal.length() - 1);
            proSubInfo.setRowTotal(rowTotal.toString());
            proSubInfo.setColTotal(colTotal.toString());
        }
        proSubInfo.setUptBy(userDtl.getId());
        proSubInfo.setUptTime(new Date());

        //更新项目风险信息-MKT_PROJECT_RISK
        //获取当前阶段
        String node = proProcessManageService.queryProProcessType(proInfo.getProCode()).getNode();
        List<ProjectRisk> riskList = vo.getProjectRisk();
        for (ProjectRisk pr : riskList) {
            pr.setAddBy(vo.getId());
            pr.setAddTime(new Date());
            pr.setRiskDesc(pr.getRiskDesc() != null ? pr.getRiskDesc() : "");
            pr.setRiskLevel(pr.getRiskLevel() != null ? pr.getRiskLevel() : "");
            pr.setSolveWay(pr.getSolveWay() != null ? pr.getSolveWay() : "");
            pr.setLatestProgress(pr.getLatestProgress() != null ? pr.getLatestProgress() : "");
            pr.setStatus(pr.getStatus() != null ? pr.getStatus() : "");
            pr.setUpdateBy(vo.getId());
            pr.setUpdateTime(new Date());
            pr.setRiskStage(node);
            pr.setProCode(vo.getProjectInfo().getProCode());
        }
        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(vo.getFileAtt()!=null){
            String[] fileAtt = vo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(userDtl, vo.getProjectInfo().getProCode(), file);
                attachmentList.add(attachment);
            }
        }
        //更新项目最新进展
        List<ProProgress> proProgresses = vo.getProProgresses();
        //项目跟踪信
        ProTrack proTracks = vo.getProTracks();
        TrackInfo trackInfo = vo.getTrackInfo();
        return  proTrackService.saveAll(proInfo,summCoopList,proSubInfo,riskList,attachmentList,proProgresses,proTracks,userDtl,submitType,bodyStr,trackInfo);
    }


}
